package org.ourgrid.broker.business.schedulerdata.executor;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import org.ourgrid.broker.business.schedulerdata.SchedulerData;
import org.ourgrid.broker.response.RemoteExecuteMessageHandleResponseTO;
import org.ourgrid.common.internal.IResponseTO;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class RemoteExecuteExecutor extends AbstractSchedulerDataExecutor {
	
	/**
	 * <REMOTE_EXECUTE workerID='String' requestID='long' commands='String'>
	 *    1..n <ENV_VAR var='String'/> 
	 * </REMOTE_EXECUTE> 
	 */
	public List<IResponseTO> execute(SchedulerData command) {
		List<IResponseTO> responses = new ArrayList<IResponseTO>();
		
		Document logDocFile = super.getXMl(command.getXml());
		
		Element element = logDocFile.getDocumentElement();
		
		String workerID = element.getAttribute("workerID");
		long requestID = Long.valueOf(element.getAttribute("requestID"));
		String commands = element.getAttribute("commands");
		
		int size = element.getElementsByTagName("ENV_VAR").getLength();
		String[] envVars = new String[size];
		
		for (int i = 0; i < size; i++) {
			envVars[i] = element.getElementsByTagName("ENV_VAR").item(i).getAttributes().
									getNamedItem("var").getNodeValue();
		}
		
		Map<String, String> vars = new LinkedHashMap<String, String>();		
		StringTokenizer tokenizer = null;
		
		for (String var : envVars) {
			tokenizer = new StringTokenizer(var, "=");
			vars.put(tokenizer.nextToken(), tokenizer.nextToken());
		}
		
		RemoteExecuteMessageHandleResponseTO to = new RemoteExecuteMessageHandleResponseTO(requestID,
				commands, vars, getAddress(workerID));
		
		responses.add(to);
		
		return responses;
	}
}
